package com.syni.mdd.yhd.common.all.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiUser.GetIdentifyingCodeDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddDistSys.FxCenterService;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.user.BmsUserDao;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.entity.user.BmsUserRegisterDisaster;
import com.syni.mdd.yhd.common.all.listen.user.UserRegisterEvent;
import com.syni.mdd.yhd.common.all.service.groupChat.BmsUserChatService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.service.record.CountBussinessActivityService;
import com.syni.mdd.yhd.common.all.service.record.ReUserRecommendService;
import com.syni.mdd.yhd.common.all.service.user.BmsUserRegisterDisasterService;
import com.syni.mdd.yhd.common.all.utils.RestTemplateUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.vo.rp.user.LoginVo;
import com.syni.mdd.yhd.common.all.vo.rp.user.MandatoryBindPhoneRpVo;
import com.syni.mdd.yhd.common.all.vo.rp.user.ThirdPartyLoginRpVo;
import com.syni.mdd.yhd.common.all.vo.rpc.UpdateAccountUserVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Service
public class BmsUserService extends BaseService<BmsUser, Integer> {

    private final Logger log = LoggerFactory.getLogger(getClass());

    public final static String virtualUserPrefix = "X009991";

    final static int loginCodeType = 1;

    final static int updatePwdCodeType = 2;

    final static int bindPhoneCodeType = 3;

    final static int mandatoryBindPhoneCodeType = 4;

    //用户类型
    final static int userType = 1;
    //商户类型
    final static int businessType = 2;

    //账号创建方式
    final static int creteByWeChat = 1;
    final static int creteByApp = 2;
    final static int createByWeChatThirdParty = 3;
    final static int createByIosLogin = 6;

    @Autowired
    BmsQhService bmsQhService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsUserBusinessFocusService bmsUserBusinessFocusService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsUserVideoLikeService bmsUserVideoLikeService;

    @Autowired
    BmsUserVideoDkService bmsUserVideoDkService;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsBusinessCodeService bmsBusinessCodeService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    CountBussinessActivityService countBussinessActivityService;

    @Autowired
    BmsUserChatService bmsUserChatService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ReUserRecommendService reUserRecommendService;

    @Autowired
    BmsUserRegisterDisasterService bmsUserRegisterDisasterService;

    @Autowired
    BmsUserDao bmsUserDao;

    @Autowired
    FxCenterService fxCenterService;

    @Override
    public BmsUserDao getBaseDao() {
        return bmsUserDao;
    }


    public BmsUser addAndSaveLocation(BmsUser bmsUser,String locationCity, String locationDistrict, String latitude, String longitude){
        if(bmsUser != null) {
            bmsUser.setLocationCity(locationCity);
            bmsUser.setLocationDistrict(locationDistrict);
            bmsUser.setLatitude(latitude);
            bmsUser.setLongitude(longitude);
            TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        }
        return bmsUser;
    }

    public SystemUser findSystemUser(String accountId){
        SystemUser systemUser = null;
        try {
            if (StringUtils.isNotBlank(accountId)) {
                String url = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/accountList";
                Map<String,Object> paramsMap = new HashMap<>();
                paramsMap.put("accountId",accountId);
                paramsMap.put("pageNo",1);
                paramsMap.put("pageSize",10);
                paramsMap.put("selectAll",0);
                String requestBody = RestTemplateUtils.postForEntityForJson(url,paramsMap);
                if(StringUtils.isNotBlank(requestBody)){
                    JSONObject userJson = JSON.parseObject(requestBody);
                    if(userJson.containsKey("status") & ResultCode.CODE_NORMAL.equals(userJson.getString("status"))){
                        JSONArray jsonArray = JSON.parseArray(userJson.getString("data"));
                        if(jsonArray.size() > 0) {
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            systemUser = JSONObject.toJavaObject(jsonObject, SystemUser.class);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("findSystemUser error",e);
        }
        return systemUser;
    }

    public BmsUser findUserByUserId(Integer userid){
        Optional<BmsUser> bmsUserOptional = bmsUserDao.findById(userid);
        if(!bmsUserOptional.isPresent()) {
            return null;
        }
        BmsUser bmsUser = bmsUserOptional.get();
        if(bmsUser != null) {
            String accountId = bmsUser.getAccountId();
            SystemUser systemUser = findSystemUser(accountId);
            bmsUser.setSystemUser(systemUser);
        }
        return bmsUser;
    }

    public BmsUser findUserByAliUserId(String aliUserId) {
        return bmsUserDao.findByAliUserId(aliUserId);
    }

    public BmsUser findUserByUnionId(String unionId){
        BmsUser bmsUser  = bmsUserDao.findByUnionid(unionId);
        if(bmsUser != null) {
            String accountId = bmsUser.getAccountId();
            if(accountId != null) {
                SystemUser systemUser = findSystemUser(accountId);
                bmsUser.setSystemUser(systemUser);
            }
        }
        return bmsUser;
    }

    public BmsUser findUserByOpenId(String openId){
        BmsUser bmsUser = bmsUserDao.findByOpenid(openId);
        if(bmsUser != null){
            try {
                String uuionId = bmsUser.getUnionid();
                if(StringUtils.isNotBlank(uuionId)){
                    String url = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/wxlogin";
                    Map<String,Object> paramsMap = new HashMap<>();
                    paramsMap.put("unionId",uuionId);
                    String requestBody = RestTemplateUtils.postForEntity(url,paramsMap);
                    if(StringUtils.isNotBlank(requestBody)){
                        JSONObject userJson = JSON.parseObject(requestBody);
                        if(userJson.containsKey("status") & ResultCode.CODE_NORMAL.equals(userJson.getString("status"))){
                            JSONObject dataJson = JSON.parseObject(userJson.getString("data"));
                            bmsUser.setSystemUser(JSONObject.toJavaObject(dataJson, SystemUser.class));
                            //兼容代码
                        }
                    }
                }
            } catch (Exception e){}finally {
                if(bmsUser.getSystemUser().getHeadImgUrl() == null) {
                    bmsUser.getSystemUser().setHeadImgUrl("");
                }
                if(bmsUser.getSystemUser().getLoginName() == null) {
                    bmsUser.getSystemUser().setLoginName("");
                }
            }
        }
        return bmsUser;
    }

    public Map<String,Object> registerLoginHandle(int loginWay, String loginBody,
                                                  String phone,Integer recommendUserId,Integer recommendBusinessId) {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        if(!PatternMatchUtils.checkPhone(phone)){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_ERROR,"手机号码格式错误");
        }
        //否为第一次登录
        final int notFirstLogin = 0;
        //是为第一次登录
        final int isFirstLogin = 1;
        //验证码登录
        final int loginWayByIdentifyCode = 1;
        //密码登录
        final int loginWayByPassword = 2;
        //返回值
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isFirstLogin",notFirstLogin);
        BmsUser bmsUser = null;
        if(loginWay == loginWayByIdentifyCode){
            //验证验证码是否正确
            if(!IdentifyCode.checkIdentifyCode(phone,loginBody,loginCodeType)){
                return ResultMapHelper.failure("验证码错误");
            }
            bmsUser = bmsUserDao.findByPhone(phone);
            if(bmsUser == null){
                Map<String,Object> registerMap = this.creatNewUser(phone,"",Constants.COMMON_FLAG_TRUE,userType);
                if(!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
                    return registerMap;
                }
                bmsUser = (BmsUser) registerMap.get("bmsUser");
                resultMap.put("isFirstLogin",isFirstLogin);
                bmsUser.setRegisterIp(requestHeaderData.getString("x-forwarded-for"));
                //判断是否是推荐注册
                if(recommendUserId != null){
                    handleRecommendUser(recommendUserId);
                    reUserRecommendService.saveHandleRecommendUser(recommendUserId,bmsUser.getId());
                }
                if(recommendBusinessId != null){
                    bmsBusinessCodeService.handleRecommendBusiness(recommendBusinessId);
                    countBussinessActivityService.handleRecommendBusiness(recommendBusinessId);
                }
            }
        }else if(loginWay == loginWayByPassword){
            //密码登录(验证密码是否正确。正确返回token)
            bmsUser = bmsUserDao.findByPhone(phone);
            if(bmsUser == null){
                return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"请先进行手机号注册");
            }
            if(bmsUser.getIsFreeze() != null && bmsUser.getIsFreeze() == Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.result(ResultCode.CODE_USER_IS_FREEZE,"账号已被冻结");
            }
            String loginUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/login";
            Map<String,Object> registerParams = new HashMap<>();
            registerParams.put("userName",phone);
            registerParams.put("passWord",loginBody);
            String requestBody = RestTemplateUtils.postForEntity(loginUrl,registerParams);
            if(!StringUtils.isNotBlank(requestBody)){
                return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
            }
            JSONObject userJson = JSON.parseObject(requestBody);
            if(!(userJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(userJson.getString("status")))){
                //累计5次错误锁住帐号
                if(userJson.getString("status").equals("30313")) {
                    return ResultMapHelper.result(userJson.getString("status"),userJson.getString("msg"));
                }else {
                    RedisTemplateUtils.getRedisTemplate().opsForZSet().incrementScore(Constants.REDIS_KEY_LOCK_PWD_ERROR, phone, 1);
                    Double errorNum = RedisTemplateUtils.getRedisTemplate().opsForZSet().score(Constants.REDIS_KEY_LOCK_PWD_ERROR, phone);
                    if (errorNum != null && errorNum > 10d) {
                        bmsUser.setIsFreeze(Constants.COMMON_FLAG_TRUE_INT);
                        TokenManager.setUser(bmsUser);
                    }
                    if (errorNum == 1d) {
                        RedisTemplateUtils.getRedisTemplate().expire(Constants.REDIS_KEY_LOCK_PWD_ERROR, 1, TimeUnit.DAYS);
                    }
                    return ResultMapHelper.result(ResultCode.CODE_USER_PWD_ERROR,"密码错误");
                }
            }
        }
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        if(bmsUser.getIsFreeze() != null && bmsUser.getIsFreeze() == Constants.COMMON_FLAG_TRUE_INT){
            return ResultMapHelper.result(ResultCode.CODE_USER_IS_FREEZE,"账号已被冻结");
        }
        //更新登录时间
        bmsUser.setLoginTime(new Date());
        bmsUserDao.save(bmsUser);
        //更新角色
        Map<String,Object> roleMap = bmsDxClientRoleService.addRegisterUserRole(bmsUser.getId(),userType);
        BmsDxClientRole bmsDxClientRole = (BmsDxClientRole) roleMap.get("data");
        //注册后续操作
        registerLoginPost(bmsUser,bmsDxClientRole.getRoleId());
        bmsUser = TokenManager.getUser(bmsUser.getId());
        //查询是否在活动期间注册
        resultMap.put("isRegisterInActivityDate",checkIsRegisterInActivityDate(roleMap));
        //判断是否加群
        resultMap.put("isRegisterGroup",bmsUserChatService.checkUserHavingGroup(bmsUser.getId(),bmsDxClientRole.getRoleId()));
        String token = TokenUtils.getToken(bmsUser,String.valueOf(BmsDxClientRoleService.generalUserRoleId));
        resultMap.put("token",token);
        resultMap.put("userid",bmsUser.getId());
        resultMap.put("phone",phone);
        resultMap.put("wechatName","");
        resultMap.put("isBindWeChat",Constants.COMMON_FLAG_FALSE_INT);
        if(StringUtils.isNotBlank(bmsUser.getUnionid())){
            resultMap.put("isBindWeChat",Constants.COMMON_FLAG_TRUE_INT);
            if(bmsUser.getSystemUser() != null && StringUtils.isNotBlank(bmsUser.getSystemUser().getLoginName())) {
                resultMap.put("wechatName", bmsUser.getSystemUser().getLoginName());
            }else {
                resultMap.put("wechatName"," ");
            }
        }
        if(StringUtils.isNotBlank(bmsUser.getIosUserId())){
            resultMap.put("isBindIos",Constants.COMMON_FLAG_TRUE_INT);
            resultMap.put("iosTag",bmsUser.getIosTag());
        }
        //分销系统角色判断
        try {
            resultMap.put("fxRole",fxCenterService.getFxRole(bmsUser.getId()));
        }catch (Exception e){
            log.info("fx Role error",e);
        }

        return ResultMapHelper.success(resultMap,"登录成功");
    }

    private void registerLoginPost(BmsUser bmsUser,Integer roleId) {
        BmsCommonService.getApplicationContext().publishEvent(new UserRegisterEvent("genUserRegister",bmsUser,roleId));
    }

    public Integer checkIsRegisterInActivityDate(Map<String,Object> roleMap){
        Integer ret = Constants.COMMON_FLAG_FALSE_INT;
        if(roleMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(roleMap.get("status").toString())){
            BmsDxClientRole bmsDxClientRole = (BmsDxClientRole) roleMap.get("data");
            Integer registerTime = DateTimeUtils.converDateToInterger(bmsDxClientRole.getNewTime());
            if(redisTemplate.hasKey(Constants.REDIS_KEY_FULL_COUPON_OPEN)){
                String activityTime = redisTemplate.opsForValue().get(Constants.REDIS_KEY_FULL_COUPON_OPEN).toString();
                String[] startEndTime = activityTime.split(",");
                Integer startTime = DateTimeUtils.converDateToInterger(DateTimeUtils.converStringToDate(startEndTime[0],DateTimeUtils.DATE_PATTERN_DAY_07));
                Integer endTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(DateTimeUtils.converStringToDate(startEndTime[1],DateTimeUtils.DATE_PATTERN_DAY_07),1));
                if(registerTime >= startTime && registerTime < endTime){
                    ret = Constants.COMMON_FLAG_TRUE_INT;
                }
            }
        }
        return ret;
    }

    /**
     * @Description 处理推荐逻辑
     * @Author: cfx
     * @Date: 2019/7/24
     */
    public void handleRecommendUser(Integer recommendUserId){
        BmsUser recommendUser = TokenManager.getUser(recommendUserId);
        if(recommendUser != null){
            recommendUser.setRecommendNum(recommendUser.getRecommendNum() == null ? 1 : recommendUser.getRecommendNum() + 1);
            TokenManager.setUser(recommendUser,TokenManager.redisKeyByUserId,recommendUser.getId().toString());
        }
    }

    /**
     * 构造电享生活号
     * @return
     */
    public String getDxshh(String dq){
        String dxshh = "";
        String qh = "999";
        //获取区号
        if(!dq.equals("") && dq!=null){
            List<BmsQh> bmsQhs = bmsQhService.getBaseDao().findByCityContaining(dq);
            if (bmsQhs!= null && bmsQhs.size() > 0){
                qh = bmsQhs.get(0).getQh();
            }
        }

        dxshh = bmsUserDao.findByDxshh();
        if(dxshh == null || dxshh.equals("")){
            return "X01"+qh+"10000";
        }else{
            String dxshhSub = dxshh.substring(7);
            if(!dxshhSub.equals("9999")){
                Integer dxshhInt =Integer.parseInt(dxshhSub);
                DecimalFormat df =new DecimalFormat("0000");
                dxshh = dxshh.substring(0,3)+ qh + "1" + df.format(dxshhInt+1);
            }else{
                DecimalFormat df =new DecimalFormat("00");
                String dxshhId = dxshh.substring(1,2);
                dxshh = "X" + df.format(Integer.parseInt(dxshhId) + 1) + qh+ "10000";
            }
        }

        return dxshh;
    }

    @Transactional
    public Map<String,Object> updateUserBaseInfo(Integer userid, String loginName,String headImg) {
        BmsUser bmsUser = TokenManager.getUser(userid);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        bmsUser.setLoginName(loginName);
        bmsUser.setHeadImg(headImg);
        //不更新到用户体系
        /*if(bmsUser.getCreateWay() == creteByApp) {
            bmsUser.getSystemUser().setLoginName(loginName);
            //更新到用户体系
            try {
                String accountId = bmsUser.getAccountId();
                if (StringUtils.isNotBlank(accountId)) {
                    String updateUserUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/updateinfo";
                    Map<String, Object> sendParams = new HashMap<String, Object>() {{
                        put("accountId", accountId);
                        put("login_name", loginName);
                    }};
                    String responseBody = RestTemplateUtils.postForEntityForJson(updateUserUrl, sendParams);
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }*/
        TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,userid.toString());
        bmsUserChatService.reloadJGGenUser(bmsUser,Constants.GENERAL_USER_ROLE_ID);
        return ResultMapHelper.success(bmsUser,ResultMsg.UPDATE_SUCCESS);
    }

    public Map<String, Object> updateUserHeadImg(Integer userid, String headImg) {
        BmsUser bmsUser = TokenManager.getUser(userid);
        if(bmsUser == null){
            return ResultMapHelper.failure("此用户不存在！");
        }
        bmsUser.setHeadImg(headImg);
        TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,userid.toString());
        return ResultMapHelper.success("修改成功！");
    }

    public Map<String, Object> updateUserPassword(Integer userId, String identifyCode,String password) {
        BmsUser bmsUser = TokenManager.getUser(userId);
        String phone = bmsUser.getPhone();
        if(phone == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_BIND,"未绑定手机号");
        }
        //验证验证码是否正确
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,updatePwdCodeType)){
            return ResultMapHelper.failure("验证码错误");
        }
        //修改密码
        String updatePwdUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/modifypwdbytel";
        Map<String,Object> sendParams = new HashMap<String,Object>(){{
            put("tel",phone);
            put("pwd",password);
        }};
        String responseBody = RestTemplateUtils.postForEntity(updatePwdUrl,sendParams);
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject jsonObject = JSON.parseObject(responseBody);
            log.info("...............账号更新信息.............." + jsonObject.toJSONString());
            if(!(jsonObject.containsKey("status") && jsonObject.getString("status").equals(ResultCode.CODE_NORMAL))){
                return ResultMapHelper.result(jsonObject.getString("status"),jsonObject.getString("msg"));
            }
            if(bmsUser.getIsSetPwd() == null || bmsUser.getIsSetPwd() == Constants.COMMON_FLAG_FALSE_INT){
                bmsUser.setIsSetPwd(Constants.COMMON_FLAG_TRUE_INT);
                TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
            }
            return ResultMapHelper.success(ResultMsg.UPDATE_SUCCESS);
        }
        return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
    }

    public String registerOperation(String phone,String password,String model){
        Map<String,Object> resultRegister = new HashMap<>();
        String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/register";
        Map<String,Object> registerParams = new HashMap<>();
        registerParams.put("userName",phone);
        registerParams.put("passWord",password);
        registerParams.put("type",model);
        String requestBody = RestTemplateUtils.postForEntity(registerUrl,registerParams);
        return requestBody;
    }

    public Map<String,Object> registerOperHand(String phone,String password,String model){
        try {
            //TODO 注册用户
            Map<String,Object> registerResultMap = new HashMap<>();
            String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/register";
            Map<String,Object> registerParams = new HashMap<>();
            registerParams.put("userName",phone);
            registerParams.put("passWord",password);
            registerParams.put("type",model);
            String requestBody = RestTemplateUtils.postForEntity(registerUrl,registerParams);
            if(!StringUtils.isNotBlank(requestBody)){
                return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
            }
            JSONObject userJson = JSON.parseObject(requestBody);
            if(userJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(userJson.getString("status"))){
                //TODO 绑定手机号
                JSONObject userRegMes = userJson.getJSONObject("data");
                String accountId = userRegMes.getString("accountId");
                registerResultMap.put("accountId",accountId);
                //绑定手机号
                Map<String,Object> retBind = userBindPhoneToSystemUser(accountId,phone);
                if(!(retBind.containsKey("status") && ResultCode.CODE_NORMAL.equals(retBind.get("status").toString()))){
                    return retBind;
                }
                return ResultMapHelper.success(registerResultMap);
            }else if(userJson.containsKey("status") && ResultCode.CODE_SYS_USER_EXIST.equals(userJson.getString("status"))){
                //直接使用返回值
                JSONObject userRegMes = userJson.getJSONObject("data");
                if(!userRegMes.containsKey("accountId")){
                    log.info("用户体系:______________缺少accountId");
                    return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"注册失败,该手机号已存在");
                }
                String accountId = userRegMes.getString("accountId");
                registerResultMap.put("accountId",accountId);
                return ResultMapHelper.success(registerResultMap);
            }else {
                return ResultMapHelper.result(userJson.getString("status"),userJson.getString("msg"));
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,e.toString());
        }
    }

    public Map<String,Object> registerOperHandNotByPhone(String phone,String password,String model){
        try {
            //TODO 注册用户
            Map<String,Object> registerResultMap = new HashMap<>();
            String registerUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/register";
            Map<String,Object> registerParams = new HashMap<>();
            registerParams.put("userName",phone);
            registerParams.put("passWord",password);
            registerParams.put("type",model);
            String requestBody = RestTemplateUtils.postForEntity(registerUrl,registerParams);
            if(!StringUtils.isNotBlank(requestBody)){
                return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
            }
            JSONObject userJson = JSON.parseObject(requestBody);
            if(userJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(userJson.getString("status"))){
                //TODO 绑定手机号
                JSONObject userRegMes = userJson.getJSONObject("data");
                String accountId = userRegMes.getString("accountId");
                registerResultMap.put("accountId",accountId);
                return ResultMapHelper.success(registerResultMap);
            }else if(userJson.containsKey("status") && ResultCode.CODE_SYS_USER_EXIST.equals(userJson.getString("status"))){
                //直接使用返回值
                JSONObject userRegMes = userJson.getJSONObject("data");
                if(!userRegMes.containsKey("accountId")){
                    log.info("用户体系:______________缺少accountId");
                    return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"注册失败,该手机号已存在");
                }
                String accountId = userRegMes.getString("accountId");
                registerResultMap.put("accountId",accountId);
                return ResultMapHelper.success(registerResultMap);
            }else {
                return ResultMapHelper.result(userJson.getString("status"),userJson.getString("msg"));
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,e.toString());
        }
    }

    /**
     * @Description: 绑定用户手机号到用户体系
     * @Author: cfx
     * @Date: 2019/6/29
     */
    public Map<String,Object> userBindPhoneToSystemUser(String accountId,String phone){
        String bindPhoneUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/relationtel";
        if(StringUtils.isBlank(accountId)){
            log.info("用户体系:______________该号缺少accountId，默认不影响觅东东手机号绑定");
            //return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
            return ResultMapHelper.success();
        }
        Map<String,Object> registerParams = new HashMap<>();
        registerParams.put("userId",accountId);
        registerParams.put("tel",phone);
        registerParams.put("type",Constants.COMMON_FLAG_TRUE_INT);
        String bindPhoneBody = null;
        try {
            bindPhoneBody = RestTemplateUtils.postForEntity(bindPhoneUrl,registerParams);
            if(StringUtils.isNotBlank(bindPhoneBody)){
                JSONObject phoneJson = JSON.parseObject(bindPhoneBody);
                if(!(phoneJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(phoneJson.getString("status")))){
                    if(phoneJson.containsKey("status") && ResultCode.CODE_USER_SYS_PHONE_EXIST.
                                    equals(phoneJson.getString("status"))){
                        return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"手机号已被绑定");
                    }
                    return ResultMapHelper.result(phoneJson.getString("status"),phoneJson.getString("msg"));
                }
                return ResultMapHelper.success();
            }
        }catch (Exception e){log.error(e.getMessage(),e);}
        log.info("---------------------用户绑定手机号数据：" + bindPhoneBody);
        return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
    }
    
    public Map<String, Object> checkBindPhoneByWeChart(String unionId) {
        BmsUser bmsUser = bmsUserDao.findByUnionid(unionId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_BIND,"未绑定手机号");
        }
        if(bmsUser.getPhone() == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_BIND,"未绑定手机号");
        }
        Map<String,Object> resultMap = new HashMap<>();
        String token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(BmsDxClientRoleService.generalUserRoleId));
        resultMap.put("token",token);
        resultMap.put("userid",bmsUser.getId());
        resultMap.put("phone",bmsUser.getPhone());
        return ResultMapHelper.success(resultMap);
    }

    public Map<String, Object> bindUserPhone(String phone,String identifyCode,
                                             String thirdCert,Integer thirdLoginWay) {
        //微信用户登录
        final int loginWayByWeiChat = 1;
        if(!PatternMatchUtils.checkPhone(phone)){
            return ResultMapHelper.failure("手机号格式错误！");
        }
        //验证验证码是否正确
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,bindPhoneCodeType)){
            return ResultMapHelper.failure("验证码错误");
        }
        BmsUser bmsUser = null;
        if(thirdLoginWay == loginWayByWeiChat){
           bmsUser = bmsUserDao.findByUnionid(thirdCert);
           if(bmsUser == null){
               //重新注册一个
               BmsUser phoneUser = bmsUserDao.findByPhone(phone);
               if(phoneUser != null){
                   return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"手机号已存在！");
               }
               Map<String,Object> registerMap = this.creatNewUser(phone,"",Constants.COMMON_FLAG_TRUE,BmsDxClientRoleService.generalUserRoleId);
               if(!(registerMap.containsKey("status") & ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
                   return registerMap;
               }
               bmsUser = (BmsUser) registerMap.get("bmsUser");
               bmsUser.setUnionid(thirdCert);
           }else {
               //绑定手机号
               //绑定手机号之前先检查手机号是否存在
               BmsUser phoneUser = bmsUserDao.findByPhone(phone);
               if(phoneUser != null){
                   return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"手机号已存在！");
               }
               String requestBody = registerOperation(phone,"",Constants.COMMON_FLAG_TRUE);
               if(!StringUtils.isNotBlank(requestBody)){
                   return ResultMapHelper.failure("用户体系接口出错！");
               }
               JSONObject userJson = JSON.parseObject(requestBody);
               if(userJson.containsKey("status") & ResultCode.CODE_SYS_USER_EXIST.equals(userJson.getString("status"))){
                   return ResultMapHelper.failure("该手机号在用户体系已被注册！");
               }
               if(userJson.containsKey("status") & ResultCode.CODE_NORMAL.equals(userJson.getString("status"))){
                   JSONObject userRegMes = JSON.parseObject(userJson.getString("data"));
                   String accountId = userRegMes.getString("accountId");
                   bmsUser.setPhone(phone);
                   bmsUser.setAccountId(accountId);
               }
           }
        }
        bmsUserDao.save(bmsUser);
        if(bmsUser == null){
            return ResultMapHelper.failure("未知错误,绑定失败！");
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("userid",bmsUser.getId());
        resultMap.put("token",TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(BmsDxClientRoleService.generalUserRoleId)));
        resultMap.put("phone",phone);
        return ResultMapHelper.success(resultMap,"绑定成功！");
    }

    @Transactional
    public BmsUser creatUser(String dxshh,String phone,String accountId,Integer userType){
        BmsUser bmsUser = bmsUserDao.findByPhone(phone);
        if(bmsUser == null) {
            bmsUser = bmsUserDao.findByAccountId(accountId);
            if(bmsUser == null) {
                bmsUser = new BmsUser();
                bmsUser.setPhone(phone);
                bmsUser.setNewTime(new Date());
                bmsUser.setAccountId(accountId);
                bmsUser.setDxshh(dxshh);
                bmsUser.setCreateWay(creteByApp);
                bmsUser.setIsSetPwd(Constants.COMMON_FLAG_FALSE_INT);
                bmsUser.setIsFreeze(Constants.COMMON_FLAG_FALSE_INT);
            }else {
                bmsUser.setPhone(phone);
            }
        }else {
            bmsUser.setAccountId(accountId);
            bmsUser.setUpdateTime(new Date());
            bmsUser.setDxshh(dxshh);
        }
        bmsUserDao.save(bmsUser);
        bmsDxClientRoleService.addRegisterUserRole(bmsUser.getId(),userType);
        return bmsUser;
    }

    @Transactional
    public BmsUser creatUserByAliUserId(String dxshh,String aliUserId,String accountId,Integer userType){
        BmsUser bmsUser = bmsUserDao.findByAliUserId(aliUserId);
        if(bmsUser == null) {
            bmsUser = bmsUserDao.findByAccountId(accountId);
            if(bmsUser == null) {
                bmsUser = new BmsUser();
                bmsUser.setAliUserId(aliUserId);
                bmsUser.setNewTime(new Date());
                bmsUser.setAccountId(accountId);
                bmsUser.setDxshh(dxshh);
                bmsUser.setCreateWay(creteByApp);
                bmsUser.setIsSetPwd(Constants.COMMON_FLAG_FALSE_INT);
                bmsUser.setIsFreeze(Constants.COMMON_FLAG_FALSE_INT);
            }else {
                bmsUser.setAliUserId(aliUserId);
            }
        }else {
            bmsUser.setAccountId(accountId);
            bmsUser.setUpdateTime(new Date());
            bmsUser.setDxshh(dxshh);
        }
        bmsUserDao.save(bmsUser);
        bmsDxClientRoleService.addRegisterUserRole(bmsUser.getId(),userType);
        return bmsUser;
    }

    public Map<String, Object> updateUserMainInfo(Integer userId,
                                                  String loginName, Integer sex, String headImg, String birthDay) {
        BmsUser bmsUser = TokenManager.getUser(userId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        String accountId = bmsUser.getAccountId();
        Map<String,Object> sendParams = new HashMap<>();
        if(loginName != null){
            bmsUser.setLoginName(loginName);
            //sendParams.put("login_name",loginName);
        }
        if(sex != null){
            bmsUser.setSex(sex);
            //用户体系代码
            final String manCode = "00";
            //用户体系男女编码
            final String womanCode = "01";
            //前端男女编码
            final int manSexCode = 0;
            String userSex = manCode;
            if(!(sex.intValue() == manSexCode)){
                userSex = womanCode;
            }
            sendParams.put("sex",userSex);
            if(bmsUser.getSystemUser() != null){
                bmsUser.getSystemUser().setSex(userSex);
            }
        }
        if(headImg != null){
            bmsUser.setHeadImg(headImg);
        }
        if(birthDay != null){
            bmsUser.setBirthday(birthDay);
            sendParams.put("birthdate",birthDay);
            if(bmsUser.getSystemUser() != null){
                bmsUser.getSystemUser().setBirthdate(DateTimeUtils.converStringToDate(birthDay,DateTimeUtils.DATE_PATTERN_DAY).getTime());
            }
        }
        TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,userId.toString());
       /* Map<Integer,Integer> updateMap = new HashMap<>();
        updateMap.put(creteByApp,Constants.COMMON_FLAG_TRUE_INT);
        if(!updateMap.containsKey(bmsUser.getCreateWay())) {
            sendParams.remove("sex");
            sendParams.remove("login_name");
        }*/
        //更新到用户体系
        if(StringUtils.isNotBlank(accountId)){
            sendParams.put("accountId",accountId);
            try {
                String updateUserUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/updateinfo";
                String responseBody = RestTemplateUtils.postForEntityForJson(updateUserUrl,sendParams);
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
        bmsUserChatService.reloadJGGenUser(bmsUser,Constants.GENERAL_USER_ROLE_ID);
        return ResultMapHelper.success(bmsUser,"修改成功");
    }

    public Map<String,Object> creatNewUser(String phone,String pwd,String model,Integer userType) {
        boolean isSetPwd = false;
        final String recordModel = "2";
        if(StringUtils.isNotBlank(pwd)){
            model = recordModel;
            isSetPwd = true;
        }
        Map<String,Object> registerMap = this.registerOperHand(phone,pwd,model);
        boolean isHandleUserRegisterDis = false;
        BmsUserRegisterDisaster bmsUserRegisterDisaster = null;
        if(!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
            //进行容错机制
            //TODO 参数持久化
            bmsUserRegisterDisaster = new BmsUserRegisterDisaster();
            Map<String,Object> content = new HashMap<>();
            content.put("phone",phone);
            content.put("pwd",pwd);
            content.put("model",model);
            content.put("userType", userType);
            bmsUserRegisterDisaster.setContent(JSON.toJSONString(content));
            String accountId = UUID.randomUUID().toString().replaceAll("-","");
            bmsUserRegisterDisaster.setAccountId(accountId);
            bmsUserRegisterDisaster.setError(JSON.toJSONString(registerMap));
            bmsUserRegisterDisaster.setNewTime(new Date());
            bmsUserRegisterDisaster.setRegisterWay(Constants.REGISTER_CREATE_NEW_USER);
            //TODO 模拟虚拟accountId
            Map<String,Object> data = new HashMap<>();
            data.put("accountId",bmsUserRegisterDisaster.getAccountId());
            registerMap = ResultMapHelper.success(data,ResultMsg.HAND_SUCCESS);
            isHandleUserRegisterDis = true;
        }
        Map<String,Object> userMap = (Map<String, Object>) registerMap.get("data");
        String accountId = userMap.get("accountId").toString();
        String cityName = ThirdInterfaceUtils.findCityByPhone(phone);
        BmsUser bmsUser = this.creatUser(this.getDxshh(cityName),phone,accountId,userType);
        if(isSetPwd){
            bmsUser.setIsSetPwd(Constants.COMMON_FLAG_TRUE_INT);
        }
        registerMap.put("bmsUser",bmsUser);
        if(isHandleUserRegisterDis){
            bmsUserRegisterDisaster.setUserId(bmsUser.getId());
            bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
        }
        return registerMap;
    }

    public Map<String,Object> creatNewUserByAliUserId(String aliUserId,String pwd,String model,Integer userType) {
        boolean isSetPwd = false;
        final String recordModel = "2";
        if(StringUtils.isNotBlank(pwd)){
            model = recordModel;
            isSetPwd = true;
        }
        Map<String,Object> registerMap = this.registerOperHandNotByPhone(aliUserId,pwd,model);
        boolean isHandleUserRegisterDis = false;
        BmsUserRegisterDisaster bmsUserRegisterDisaster = null;
        if(!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
            //进行容错机制
            //TODO 参数持久化
            bmsUserRegisterDisaster = new BmsUserRegisterDisaster();
            Map<String,Object> content = new HashMap<>();
            content.put("phone",aliUserId);
            content.put("pwd",pwd);
            content.put("model",model);
            content.put("userType", userType);
            bmsUserRegisterDisaster.setContent(JSON.toJSONString(content));
            String accountId = UUID.randomUUID().toString().replaceAll("-","");
            bmsUserRegisterDisaster.setAccountId(accountId);
            bmsUserRegisterDisaster.setError(JSON.toJSONString(registerMap));
            bmsUserRegisterDisaster.setNewTime(new Date());
            bmsUserRegisterDisaster.setRegisterWay(Constants.REGISTER_NEW_USER_ALI);
            //TODO 模拟虚拟accountId
            Map<String,Object> data = new HashMap<>();
            data.put("accountId",bmsUserRegisterDisaster.getAccountId());
            registerMap = ResultMapHelper.success(data,ResultMsg.HAND_SUCCESS);
            isHandleUserRegisterDis = true;
        }
        Map<String,Object> userMap = (Map<String, Object>) registerMap.get("data");
        String accountId = userMap.get("accountId").toString();
        String cityName = ThirdInterfaceUtils.findCityByPhone(aliUserId);
        BmsUser bmsUser = this.creatUserByAliUserId(this.getDxshh(cityName),aliUserId,accountId,userType);
        if(isSetPwd){
            bmsUser.setIsSetPwd(Constants.COMMON_FLAG_TRUE_INT);
        }
        registerMap.put("bmsUser",bmsUser);
        if(isHandleUserRegisterDis){
            bmsUserRegisterDisaster.setUserId(bmsUser.getId());
            bmsUserRegisterDisasterService.getBaseDao().save(bmsUserRegisterDisaster);
        }
        return registerMap;
    }

    public boolean checkSetPassword(String phone) {
        boolean ret = false;
        if(StringUtils.isNotBlank(phone)) {
            try {
                String loginUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/login";
                Map<String, Object> registerParams = new HashMap<>();
                registerParams.put("userName", phone);
                registerParams.put("passWord", "");
                String requestBody = RestTemplateUtils.postForEntity(loginUrl, registerParams);
                JSONObject userJson = JSON.parseObject(requestBody);
                if (userJson.containsKey("status") && ResultCode.CODE_USER_NO_SET_PWD.equals(userJson.getString("status"))) {
                    ret = false;
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return ret;
    }

    public Map<String, Object> getMyFocusBusiness(Integer userId,Integer pageNum,Integer pageSize) {
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize,Sort.Direction.DESC,"newTime");
        List<BmsUserBusinessFocus> bmsUserBusinessFocusList = bmsUserBusinessFocusService.findUserFouce(userId,pageable);
        Set businessIds = new HashSet();
        if(bmsUserBusinessFocusList != null && bmsUserBusinessFocusList.size() > 0){
            for(BmsUserBusinessFocus bmsUserBusinessFocus : bmsUserBusinessFocusList){
                businessIds.add(bmsUserBusinessFocus.getBmsBusinessId());
            }
        }
        List<Map<String,Object>> resultList = new LinkedList<>();
        if(businessIds.size() > 0){
            List<BmsBusiness> bmsBusinesses  = bmsBusinessService.getBaseDao().findByIdIn(businessIds);
            if(bmsBusinesses.size() > 0){
                for(BmsBusiness bmsBusiness : bmsBusinesses){
                    Map<String,Object> bmMap = new HashMap<>();
                    bmMap.put("id",bmsBusiness.getId());
                    bmMap.put("vendor_name",bmsBusiness.getVendorName());
                    bmMap.put("logo_url",bmsBusiness.getLogoUrl());
                    resultList.add(bmMap);
                }
            }

        }
        return ResultMapHelper.success(resultList,"获取成功");
    }

    public Map<String,Object> thirdPartyLogin(ParamsMap paramsMap) {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        //微信第三方登陆
        final int LOGIN_WAY_FOR_WEChAT = 1;
        //苹果第三方登陆
        final int LOGIN_WAY_FOR_IOS = 2;
        Integer loginWay = Integer.parseInt(paramsMap.get("login_way").toString());
        ThirdPartyLoginRpVo thirdPartyLoginRpVo = new ThirdPartyLoginRpVo();
        /*Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isBindPhone", Constants.COMMON_FLAG_FALSE_INT);
        resultMap.put("isFirstLogin",Constants.COMMON_FLAG_FALSE_INT);*/
        BmsUser bmsUser = null;
        boolean isCreateUser = false;
        SystemUser systemUser = null;
        if(loginWay == LOGIN_WAY_FOR_WEChAT) {
            final String sysUserLady = "01";
            if(!(StringUtils.checkNullAndEmpty(paramsMap.get("union_id")) &&
                    StringUtils.checkNullAndEmpty(paramsMap.get("access_token")) &&
                    StringUtils.checkNullAndEmpty(paramsMap.get("open_id")))) {
                return ResultMapHelper.failure("微信登录回调参数缺失");
            }
            String unionId = paramsMap.get("union_id").toString();
            String accessToken = paramsMap.get("access_token").toString();
            String openId = paramsMap.get("open_id").toString();
            bmsUser = bmsUserDao.findByUnionid(unionId);
            JSONObject userJson = WeChartUtils.findWeChatUserInfo(openId, accessToken);
            if (!(userJson.size() > 0)) {
                return ResultMapHelper.failure("无法获取微信用户信息");
            }
            if (bmsUser == null) {
                isCreateUser = true;
                thirdPartyLoginRpVo.setIsFirstLogin(Constants.COMMON_FLAG_TRUE_INT);
                systemUser = JSONObject.toJavaObject(userJson, SystemUser.class);
                if (userJson.containsKey("nickname")) {
                    systemUser.setLoginName(userJson.getString("nickname"));
                }
                if (userJson.containsKey("headimgurl") && StringUtils.checkNullAndEmpty(userJson.get("headimgurl"))) {
                    systemUser.setHeadImgUrl(userJson.getString("headimgurl"));
                }
                systemUser.setUnionId(unionId);
                bmsUser = new BmsUser();
                bmsUser.setDxshh(getDxshh(systemUser.getCity()));
                bmsUser.setLoginName(systemUser.getLoginName());
                bmsUser.setSex(Constants.COMMON_FLAG_TRUE_INT);
                if (systemUser.getSex().equals(sysUserLady)) {
                    bmsUser.setSex(Constants.COMMON_FLAG_FALSE_INT);
                }
                bmsUser.setNewTime(new Date());
                bmsUser.setUpdateTime(new Date());
                bmsUser.setLocationCity(systemUser.getCity());
                bmsUser.setUnionid(unionId);
                bmsUser.setCreateWay(BmsUserService.createByWeChatThirdParty);
                bmsUser.setIsSetPwd(Constants.COMMON_FLAG_FALSE_INT);
                bmsUser.setRegisterIp(requestHeaderData.getString("x-forwarded-for"));
            } else {
                //有了
                bmsUser = TokenManager.getUser(bmsUser.getId());
                systemUser = bmsUser.getSystemUser();
                if(systemUser == null){
                    systemUser = new SystemUser();
                    systemUser.setUnionId(unionId);
                }else {
                    if(StringUtils.isBlank(systemUser.getUnionId())){
                        systemUser.setUnionId(unionId);
                    }
                }
                if (userJson.containsKey("nickname")) {
                    systemUser.setLoginName(userJson.getString("nickname"));
                }
                
                if (StringUtils.isNotBlank(bmsUser.getPhone())) {
                    thirdPartyLoginRpVo.setIsBindPhone(Constants.COMMON_FLAG_TRUE_INT);
                    //resultMap.put("isBindPhone", Constants.COMMON_FLAG_TRUE_INT);
                }
            }
            bmsUser.setAppOpenid(openId);
            //往用户体系注册/更新
            systemUser.setUserId(bmsUser.getId());
            Map<String, Object> registerRet = WeChartUtils.addUserToUserSystem(systemUser,false);
            if (!(boolean) registerRet.get("status")) {
                return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
            }
            if(bmsUser == null){
                return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
            }
            if(bmsUser.getIsFreeze() != null && bmsUser.getIsFreeze() == Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.result(ResultCode.CODE_USER_IS_FREEZE,"账号已被冻结");
            }
            JSONObject registerData = (JSONObject) registerRet.get("data");
            if (registerData != null) {
                if (registerData.containsKey("accountId")) {
                    String accountId = registerData.getString("accountId");
                    BmsUser accountUser = bmsUserDao.findByAccountId(accountId);
                    if(accountUser != null){
                        if(!bmsUser.getId().equals(accountUser.getId())) {
                            accountUser.setAccountId(null);
                            TokenManager.setUser(accountUser);
                        }
                    }
                    bmsUser.setAccountId(accountId);
                }
                if(registerData.containsKey("loginName") && !StringUtils.checkNullAndEmpty(bmsUser.getLoginName())){
                    bmsUser.setLoginName(registerData.getString("loginName"));
                }
                if(registerData.containsKey("headImgUrl") && !StringUtils.checkNullAndEmpty(bmsUser.getHeadImg())){
                    bmsUser.setHeadImg(registerData.getString("headImgUrl"));
                }
            }
        }else if(loginWay == LOGIN_WAY_FOR_IOS){
            String iosAuthCode = paramsMap.getString("iosAuthCode");
            String iosUserId = paramsMap.getString("iosUserId");
            JSONObject data;
            try {
                data = this.getIosLoginData(iosAuthCode);
                //data = new JSONObject();
                //data.put("sub","001863.a982eae71f4b4ae6bd5b404e8ef3f420.0350");
                //data.put("email","843010518@qq.com");
                if(data.containsKey("sub") && StringUtils.checkNullAndEmpty(data.get("sub"))){
                    String sub = data.getString("sub");
                    String email = data.getString("email");
                    if(!sub.equals(iosUserId)){
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_PARAM_ERROR);
                    }
                    bmsUser = bmsUserDao.findByIosUserId(iosUserId);
                    if(bmsUser == null){
                        thirdPartyLoginRpVo.setIsFirstLogin(Constants.COMMON_FLAG_TRUE_INT);
                        bmsUser = new BmsUser();
                        bmsUser.setDxshh(getDxshh(""));
                        bmsUser.setCreateWay(BmsUserService.createByIosLogin);
                        bmsUser.setRegisterIp(requestHeaderData.getString("x-forwarded-for"));
                        bmsUser.setIosUserId(iosUserId);

                        //往用户体系注册
                        Map<String,Object> resultMap = WeChartUtils.registerUserByIosUserId(iosUserId);
                        if (!(boolean) resultMap.get("status")) {
                            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_PARAM_ERROR);
                        }
                        JSONObject registerData = (JSONObject) resultMap.get("data");
                        if (registerData != null) {
                            if (registerData.containsKey("accountId")) {
                                String accountId = registerData.getString("accountId");
                                BmsUser accountUser = bmsUserDao.findByAccountId(accountId);
                                if(accountUser != null){
                                    accountUser.setAccountId(null);
                                    TokenManager.setUser(accountUser);
                                }
                                bmsUser.setAccountId(accountId);
                            }
                        }
                    }
                    bmsUser.setIosTag(email);
                }
            }catch (Exception e){
                log.error("ios login error : ",e);
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
            }
        }
        //更新登录时间
        bmsUser.setLoginTime(new Date());
        log.info("bmsUser data：" + JSON.toJSONString(bmsUser));
        bmsUserDao.save(bmsUser);
        bmsUser.setSystemUser(systemUser);
        //更新到redis
        //bmsUser = TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        registerLoginPost(bmsUser,Constants.GENERAL_USER_ROLE_ID);
        //更新角色
        Map<String,Object> roleMap = bmsDxClientRoleService.addRegisterUserRole(bmsUser.getId(),userType);
        //查询是否在活动期间注册
        thirdPartyLoginRpVo.setIsRegisterInActivityDate(checkIsRegisterInActivityDate(roleMap));
        String token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(BmsDxClientRoleService.generalUserRoleId));
        thirdPartyLoginRpVo.setToken(token);
        thirdPartyLoginRpVo.setUnionId(bmsUser.getUnionid());
        thirdPartyLoginRpVo.setPhone(bmsUser.getPhone());
        thirdPartyLoginRpVo.setHeadImgUrl(bmsUser.getHeadImg());
        thirdPartyLoginRpVo.setLoginName(bmsUser.getLoginName());
        thirdPartyLoginRpVo.setIsRegisterGroup(bmsUserChatService.checkUserHavingGroup(bmsUser.getId(),Constants.GENERAL_USER_ROLE_ID));
        //thirdPartyLoginRpVo.setFxRole(fxCenterService.getFxRole(bmsUser.getId()));
        thirdPartyLoginRpVo.setUserid(bmsUser.getId());
        /*resultMap.put("isRegisterInActivityDate",checkIsRegisterInActivityDate(roleMap));
        resultMap.put("token",token);
        resultMap.put("unionId",bmsUser.getUnionid());
        resultMap.put("userid",bmsUser.getId());
        resultMap.put("phone",bmsUser.getPhone());
        resultMap.put("headImgUrl",bmsUser.getHeadImg());
        resultMap.put("loginName",bmsUser.getLoginName());
        resultMap.put("isRegisterGroup",bmsUserChatService.checkUserHavingGroup(bmsUser.getId(),Constants.GENERAL_USER_ROLE_ID));
        resultMap.put("isBindPhone",Constants.COMMON_FLAG_FALSE_INT);
        resultMap.put("fxRole",fxCenterService.getFxRole(bmsUser.getId()));*/
        thirdPartyLoginRpVo.setFxRole(fxCenterService.getFxRole(bmsUser.getId()));
        if(StringUtils.isNotBlank(bmsUser.getPhone())){
            thirdPartyLoginRpVo.setIsBindPhone(Constants.COMMON_FLAG_TRUE_INT);
            //resultMap.put("isBindPhone",Constants.COMMON_FLAG_TRUE_INT);
        }
        //统计推荐情况
        if(isCreateUser){
            if(paramsMap.containsKey("recommend_user") && StringUtils.checkNullAndEmpty(paramsMap.get("recommend_user"))){
                handleRecommendUser(Integer.parseInt(paramsMap.get("recommend_user").toString()));
                reUserRecommendService.saveHandleRecommendUser(Integer.parseInt(paramsMap.get("recommend_user").toString()),bmsUser.getId());
            }
            if(paramsMap.containsKey("recommend_business") && StringUtils.checkNullAndEmpty(paramsMap.get("recommend_business"))){
                Integer businessId = Integer.parseInt(paramsMap.get("recommend_business").toString());
                bmsBusinessCodeService.handleRecommendBusiness(businessId);
                countBussinessActivityService.handleRecommendBusiness(businessId);
            }
        }
        if(StringUtils.isNotBlank(bmsUser.getUnionid())){
            if(bmsUser.getSystemUser() != null && StringUtils.isNotBlank(bmsUser.getSystemUser().getLoginName())) {
                //resultMap.put("wechatName", bmsUser.getSystemUser().getLoginName());
                thirdPartyLoginRpVo.setWechatName(bmsUser.getSystemUser().getLoginName());
            }else{
                //resultMap.put("wechatName"," ");
                thirdPartyLoginRpVo.setWechatName(" ");
            }
        }
        if(StringUtils.isNotBlank(bmsUser.getIosUserId())){
            thirdPartyLoginRpVo.setIsBindIos(Constants.COMMON_FLAG_TRUE_INT);
            thirdPartyLoginRpVo.setIosTag(bmsUser.getIosTag());
        }
        return ResultMapHelper.success(thirdPartyLoginRpVo,"登录成功");
    }

    private JSONObject getIosLoginData(String iosAuthCode) throws Exception {
        final String CLIENT_ID = "com.syni.MDDUser";    // 被授权的APP ID
        final String KID = "WTGGKR54P2";
        final String TERM_ID = "JW7ZG29B45";
        long now = System.currentTimeMillis() / 1000;
        Map<String, Object> header = new HashMap<String, Object>();
        header.put("kid", KID); // 参考后台配置
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("iss", TERM_ID); // 参考后台配置 team id
        claims.put("iat", now);
        claims.put("exp", now + 86400 * 30); // 最长半年，单位秒
        claims.put("aud", "https://appleid.apple.com"); // 默认值
        claims.put("sub", CLIENT_ID);
        byte[] privateKeyParams = Base64.getDecoder().decode("MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgZZvcsYd+IamT9ckQFmPueIJKnPsRwugVDFkEtRb9yCGgCgYIKoZIzj0DAQehRANCAAQjXpacbIkM5Bj3oZF5PfAqzV6CRDxC8PWobP5ckcMOXXsz9iengChonfCEL930Xk1d6/du2wHPkiunEDoRkJG8");
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyParams);
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        String client_secret = Jwts.builder().setHeader(header).setClaims(claims).signWith(SignatureAlgorithm.ES256, privateKey).compact();

        String url = "https://appleid.apple.com/auth/token";
        Map<String, Object> form = new HashMap<>();
        form.put("client_id", CLIENT_ID);
        form.put("client_secret", client_secret);
        form.put("code", iosAuthCode);
        form.put("grant_type","authorization_code");
        String responseBody = RestTemplateUtils.postForEntity(url,form);
        Map<String,Object> returnBody = JSON.parseObject(responseBody);
        String idToken = returnBody.get("id_token").toString();
        String[] identityTokens = idToken.split("\\.");
        String str = new String(Base64Utils.decodeFromString(identityTokens[1]), "UTF-8");
        JSONObject data = JSONObject.parseObject(str);
        return data;
    }

    @Transactional
    public Map<String,Object> userBindWx(Map<String,Object> paramsMap){
        
        Map<String, Object> resultMap = new HashMap<>();
        BmsUser bmsUser = null;
        SystemUser systemUser = null;
        
        BmsUser nowBmsUser = null;
        SystemUser nowSystemUser = null;
//        if(!(StringUtils.checkAnyNotNull(paramsMap.get("unionId")) &&
//                StringUtils.checkAnyNotNull(paramsMap.get("userIdentify")) &&
//                StringUtils.checkAnyNotNull(paramsMap.get("openId"))) &&
//                StringUtils.checkAnyNotNull(paramsMap.get("accessToken"))) {
//            return ResultMapHelper.failure("微信参数缺失");
//        }
        //如果微信被绑定过  是否强制绑定    0否 1是
//        String isForce = paramsMap.get("isForce").toString();
        String unionId = paramsMap.get("unionId").toString();
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        String openId = paramsMap.get("openId").toString();
        String accessToken = paramsMap.get("accessToken").toString();

        JSONObject userJson = WeChartUtils.findWeChatUserInfo(openId, accessToken);
        if (!(userJson.size() > 0) || userJson.containsKey("errcode")) {
            return ResultMapHelper.failure("无法获取微信用户信息");
        }


        nowBmsUser = TokenManager.getUser(userId);

        if(nowBmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        if(StringUtils.checkNullAndEmpty(nowBmsUser.getUnionid()) && nowBmsUser.getUnionid().equals(unionId)) {
            return ResultMapHelper.result(ResultCode.CODE_USER_WX_BIND_USER,"用户已绑定该微信");
        }

        bmsUser = bmsUserDao.findByUnionid(unionId);
//        if("0".equals(isForce) && bmsUser != null) {
//            return ResultMapHelper.result(ResultCode.CODE_USER_WX_BIND,"该微信已被绑定");
//        }
        if(bmsUser!=null && StringUtils.checkAnyNotNull(bmsUser.getPhone())){
            return ResultMapHelper.result(ResultCode.CODE_USER_WX_BIND,"该微信号已被绑定，请联系客服处理");
        }

        if (bmsUser != null) {
            //有了   清除掉
            bmsUser.setUnionid(null);
            bmsUser.setOpenid(null);
            bmsUser.setAppOpenid(null);
            bmsUser.setMinOpenid(null);
            String accountId = bmsUser.getAccountId();
            systemUser = bmsUser.getSystemUser();
            systemUser.setAccountId(accountId);
            systemUser.setUserId(bmsUser.getId());
            systemUser.setUnionId(null);
            Map<String, Object> registerRet = WeChartUtils.relationWx(systemUser);
            if (!(boolean) registerRet.get("status")) {
                return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
            }
            bmsUserDao.save(bmsUser);
            //同时将小程序的登录强制下线
            String userTokenKey = Constants.REDIS_KEY_TOKEN + String.format("%s:%s:%s",userId,Constants.GENERAL_USER_ROLE_ID,Constants.SMALL_PROGRAM);
            TokenUtils.cancellation(userTokenKey);
        }

        nowSystemUser = JSONObject.toJavaObject(userJson, SystemUser.class);
        if (userJson.containsKey("nickname") && StringUtils.checkNullAndEmpty(userJson.get("nickname"))) {
            if(!StringUtils.checkNullAndEmpty(nowBmsUser.getLoginName())) {
                nowBmsUser.setLoginName(userJson.getString("nickname"));
            }
            nowSystemUser.setLoginName(userJson.getString("nickname"));
        }
        if (userJson.containsKey("headimgurl") && StringUtils.checkNullAndEmpty(userJson.get("headimgurl"))) {
            if(!StringUtils.checkNullAndEmpty(nowBmsUser.getHeadImg())) {
                nowBmsUser.setHeadImg(userJson.getString("headimgurl"));
            }
            nowSystemUser.setHeadImgUrl(userJson.getString("headimgurl"));
        }

        nowBmsUser.setUpdateTime(new Date());
        nowBmsUser.setAppOpenid(openId);
        nowBmsUser.setUnionid(unionId);

        //往用户体系更新
        nowSystemUser.setAccountId(nowBmsUser.getAccountId());
        nowSystemUser.setUnionId(unionId);
        nowSystemUser.setUserId(nowBmsUser.getId());

        Map<String, Object> BindRet = WeChartUtils.relationWx(nowSystemUser);
        if (!(boolean) BindRet.get("status")) {
            return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
        }
        nowBmsUser.setSystemUser(nowSystemUser);
        log.info("nowBmsUser信息：" + JSON.toJSONString(nowBmsUser));
        bmsUserDao.save(nowBmsUser);
        //更新到redis
        TokenManager.setUser(nowBmsUser,TokenManager.redisKeyByUserId,nowBmsUser.getId().toString());
        if(bmsUser != null) {
        	bmsUser.setSystemUser(systemUser);
        	TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        }
        resultMap.put("headImg", nowBmsUser.getHeadImg());
        resultMap.put("loginName", nowBmsUser.getLoginName());

        return ResultMapHelper.success(resultMap,"微信绑定成功");
    }
   
    public Map<String,Object> untyingBindWx(Integer userId){
    	BmsUser bmsUser = TokenManager.getUser(userId);
    	if(bmsUser != null) {
    		if(StringUtils.checkNullAndEmpty(bmsUser.getUnionid())) {
    			bmsUser.setUnionid(null);
    			bmsUser.setOpenid(null);
    			bmsUser.setAppOpenid(null);
    			bmsUser.setMinOpenid(null);
    		}else {
    			return ResultMapHelper.result(ResultCode.CODE_USER_WX_NO_BIND,"该账户未绑定微信");
    		}
    		
    		if(!StringUtils.checkNullAndEmpty(bmsUser.getPhone())) {
    			return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_NO_BIND,"您未绑定手机号，解绑微信后将无法登录，请您先绑定手机号再解绑微信");
    		}
    	}else {
    		return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
    	}
    	String accountId = bmsUser.getAccountId();
    	SystemUser systemUser = bmsUser.getSystemUser();
		systemUser.setAccountId(accountId);
		systemUser.setUserId(bmsUser.getId());
		systemUser.setUnionId(null);
        Map<String,Object> retBind = WeChartUtils.relationWx(systemUser);
        
        if (!(boolean) retBind.get("status")) {
            return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
        }
        
    	TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
    	Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("userid",userId);
        //同时将小程序的登录强制下线
        String userTokenKey = Constants.REDIS_KEY_TOKEN + String.format("%s:%s:%s",userId,Constants.GENERAL_USER_ROLE_ID,Constants.SMALL_PROGRAM);
        TokenUtils.cancellation(userTokenKey);
        return ResultMapHelper.success(resultMap,"微信解绑成功");
    }
    
    public Map<String, Object> userBindPhone(Integer userId,String phone,String identifyCode) {
        if(!PatternMatchUtils.checkPhone(phone)){
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_ERROR,"手机号码格式错误");
        }
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,bindPhoneCodeType)){
            return ResultMapHelper.result(ResultCode.CODE_IDENTIFY_CODE_ERROR,ResultMsg.CODE_IDENTIFY_CODE_ERROR);
        }
        BmsUser bmsUser = bmsUserDao.findByPhone(phone);
        if(bmsUser!= null){
            if(userId.intValue() == bmsUser.getId().intValue()){
                return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_BIND_USER,"你当前已经绑定该手机号");
            }
            return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"手机号已被绑定");
        }
        bmsUser = TokenManager.getUser(userId);
        String accountId = bmsUser.getAccountId();
        Map<String,Object> retBind = userBindPhoneToSystemUser(accountId,phone);
        if(!(retBind.containsKey("status") && ResultCode.CODE_NORMAL.equals(retBind.get("status").toString()))){
            return retBind;
        }
        bmsUser.setPhone(phone);
        TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("phone",phone);
        resultMap.put("userid",userId);
        return ResultMapHelper.success(resultMap,"绑定成功");
    }

    /*public Map<String, Object> mandatoryBindPhone(Integer userId, String phone, String identifyCode,Integer bindClient) {
        return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
    }*/

    public Map<String, Object> watchVideoInteractive(Integer userId, List<Integer> videoIds) {
        //是否点赞，是否打卡
        Set<Integer> videoIdsSet = new HashSet<>();
        for(Integer videoId : videoIds){
            videoIdsSet.add(videoId);
        }
        List<Integer> videoLikeList = new LinkedList<>();
        List<Integer> videoDkList = new LinkedList<>();
        if(videoIdsSet.size() > 0) {
            List<Map<String, Object>> bmsUserVideoLikes = bmsUserVideoLikeService.getByUserIdAndVideoIdIn(userId, videoIdsSet);
            if (bmsUserVideoLikes != null && bmsUserVideoLikes.size() > 0) {
                for (Map<String, Object> bmsUserVideoLike : bmsUserVideoLikes) {
                    videoLikeList.add(Integer.parseInt(bmsUserVideoLike.get("bms_video_id").toString()));
                }
            }
            //先找出对应视频的商家id
            Map<Integer,List<Integer>> businessIdAndVideoId = bmsVideoService.findVideosBussessIds(videoIdsSet);
            if (businessIdAndVideoId.size() > 0) {
                List<BmsUserVideoDk> bmsUserVideoDkList = bmsUserVideoDkService.getUserDkByUserIdAndBusinessIdIn(userId, businessIdAndVideoId.keySet());
                if (bmsUserVideoDkList != null && bmsUserVideoDkList.size() > 0) {
                    for (BmsUserVideoDk bmsUserVideoDk : bmsUserVideoDkList) {
                        if(businessIdAndVideoId.containsKey(bmsUserVideoDk.getBmsBusinessId())){
                            videoDkList.addAll(businessIdAndVideoId.get(bmsUserVideoDk.getBmsBusinessId()));
                        }
                    }
                }
            }
        }
        List<Map<String,Object>> resultMap = new LinkedList<>();
        for(Integer videoId : videoIdsSet){
            Map<String,Object> singleResult = new HashMap<>();
            singleResult.put("videoId",videoId);
            singleResult.put("isLike",Constants.COMMON_FLAG_FALSE_INT);
            singleResult.put("isDk",Constants.COMMON_FLAG_FALSE_INT);
            if(videoLikeList.contains(videoId)){
                singleResult.put("isLike",Constants.COMMON_FLAG_TRUE_INT);
            }
            if(videoDkList.contains(videoId)){
                singleResult.put("isDk",Constants.COMMON_FLAG_TRUE_INT);
            }
            resultMap.add(singleResult);
        }
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String,Object> updateFreezeStatus(Integer userId,Integer status) {
        BmsUser bmsUser = TokenManager.getUser(userId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        bmsUser.setIsFreeze(status);
        TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        return ResultMapHelper.success(null,ResultMsg.UPDATE_SUCCESS);
    }

    @Transactional
    public Map<String, Object> mandatoryBindPhone(Integer userId, String phone, String identifyCode,Integer bindClient) {
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,bindPhoneCodeType,mandatoryBindPhoneCodeType)){
            return ResultMapHelper.failure("验证码错误");
        }
        BmsUser bmsUser = TokenManager.getUser(userId);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        BmsUser originalBmsUser = bmsUserDao.findByPhone(phone);
        if(bmsUser.getCreateWay() == null || bmsUser.getCreateWay() == creteByApp){
            if(originalBmsUser != null){
                //调用用户体系强制绑定
                Map<String,Object> retBind = userBindPhoneToSystemUser(bmsUser.getAccountId(),phone);
                if(!(retBind.containsKey("status") && ResultCode.CODE_NORMAL.equals(retBind.get("status").toString()))){
                    return retBind;
                }
                originalBmsUser.setPhone(null);
                TokenManager.setUser(originalBmsUser,TokenManager.redisKeyByUserId,originalBmsUser.getId().toString());
            }
        }else if(bmsUser.getCreateWay() == creteByWeChat || bmsUser.getCreateWay() == createByWeChatThirdParty){
            if (originalBmsUser != null) {
                //仍需判断原来的手机是否已经绑了手机号了
                if(StringUtils.isNotBlank(bmsUser.getPhone())){
                    Map<String,Object> retBind = userBindPhoneToSystemUser(bmsUser.getAccountId(),phone);
                    if(!(retBind.containsKey("status") && ResultCode.CODE_NORMAL.equals(retBind.get("status").toString()))){
                        return retBind;
                    }
                    originalBmsUser.setPhone(null);
                    TokenManager.setUser(originalBmsUser,TokenManager.redisKeyByUserId,originalBmsUser.getId().toString());
                }else {
                    String openId = bmsUser.getOpenid();
                    String unionId = bmsUser.getUnionid();
                    String minOpenId = bmsUser.getMinOpenid();
                    String appOpenId = bmsUser.getAppOpenid();
                    bmsUser.setOpenid(null);
                    bmsUser.setUnionid(null);
                    bmsUser.setMinOpenid(null);
                    bmsUser.setAppOpenid(null);
                    TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
                    originalBmsUser.setOpenid(openId);
                    originalBmsUser.setUnionid(unionId);
                    originalBmsUser.setMinOpenid(minOpenId);
                    originalBmsUser.setAppOpenid(appOpenId);
                    originalBmsUser.setUpdateTime(new Date());
                    bmsUser = originalBmsUser;
                    //调用用户体系做账号合并
                    Map<String,Object> retBind = userMergeAccount(unionId,phone);
                    if(!(retBind.containsKey("status") && ResultCode.CODE_USER_SYS_MERGE_ACCOUNT_SUCCESS.equals(retBind.get("status").toString()))){
                        return retBind;
                    }
                }
            }
        }else if(bmsUser.getCreateWay().equals(createByIosLogin)){
            if(originalBmsUser != null){
                String iosUserId = bmsUser.getIosUserId();
                String iosTag = bmsUser.getIosTag();
                bmsUser.setIosTag(null);
                bmsUser.setIosUserId(null);
                originalBmsUser.setIosUserId(iosUserId);
                originalBmsUser.setIosTag(iosTag);
                TokenManager.setUser(bmsUser);
                TokenManager.setUser(originalBmsUser);
                bmsUser = originalBmsUser;
            }
        }
        else {
            return ResultMapHelper.failure("暂不支持该种绑定方式");
        }
        bmsUser.setPhone(phone);
        bmsUser.setUpdateTime(new Date());
        TokenManager.setUser(bmsUser);
        MandatoryBindPhoneRpVo mandatoryBindPhoneRpVo = new MandatoryBindPhoneRpVo();
        mandatoryBindPhoneRpVo.setUserid(userId);
        mandatoryBindPhoneRpVo.setPhone(bmsUser.getPhone());
        mandatoryBindPhoneRpVo.setToken(TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(Constants.GENERAL_USER_ROLE_ID)));
        return ResultMapHelper.success(mandatoryBindPhoneRpVo,"绑定成功");
    }

    public Map<String,Object> userMergeAccount(String unionId, String phone) {
        String mergeAccount = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/mergeAccount";
        Map<String,Object> registerParams = new HashMap<>();
        registerParams.put("phoneNo",phone);
        registerParams.put("unionId",unionId);
        String bindPhoneBody = null;
        try {
            bindPhoneBody = RestTemplateUtils.postForEntity(mergeAccount,registerParams);
            if(StringUtils.isNotBlank(bindPhoneBody)){
                JSONObject phoneJson = JSON.parseObject(bindPhoneBody);
                if(!(phoneJson.containsKey("status") && ResultCode.CODE_NORMAL.equals(phoneJson.getString("status")))){
                    return ResultMapHelper.result(phoneJson.getString("status"),phoneJson.getString("msg"));
                }
                return ResultMapHelper.success();
            }
        }catch (Exception e){log.error(e.getMessage(),e);}
        return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
    }

    public Map<String, Object> getMyFocusVideo(Integer userId,Integer pageNum,Integer pageSize,
                                               String latitude,String longitude) {
        //查找用户关注的商家
        List<BmsVideo> bmsVideos = new LinkedList<>();
        List<BmsUserBusinessFocus> bmsUserBusinessFocusList = bmsUserBusinessFocusService.findUserFouce(userId);
        if(bmsUserBusinessFocusList != null && bmsUserBusinessFocusList.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            for(BmsUserBusinessFocus bmsUserBusinessFocus : bmsUserBusinessFocusList){
                businessIds.add(bmsUserBusinessFocus.getBmsBusinessId());
            }
            if(businessIds.size() > 0){
                Map<String,Object> conditionMap = new HashMap<>();
                conditionMap.put("isDelete", Constants.COMMON_FLAG_FALSE_INT);
                conditionMap.put("isRelease", Constants.COMMON_FLAG_FALSE_INT);
                conditionMap.put("isOff", Constants.COMMON_FLAG_FALSE_INT);
                conditionMap.put("bmsId_IN",businessIds);
                Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
                bmsVideos.addAll(bmsVideoService.getBaseDao().findAll(new SpecificationUtils(conditionMap),pageable).getContent());
            }
        }
        if(bmsVideos.size() > 0){
            bmsVideoService.getListPostForVideoList(bmsVideos,userId.toString());
            bmsVideoService.calculatedDistance(bmsVideos, latitude, longitude);
            bmsVideoService.setIsOpenCouponAndGroupBuy(bmsVideos);
        }
        return ResultMapHelper.success(bmsVideos,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<Integer, BmsUser> getUserByIds(Set<Integer> userIds) {
        Map<Integer,BmsUser> bmsUserMap = new HashMap<>();
        if(userIds.size() > 0){
            List<BmsUser> bmsUsers = bmsUserDao.findByIdIn(userIds);
            if(bmsUsers != null && bmsUsers.size() > 0){
                for(BmsUser bmsUser : bmsUsers){
                    bmsUserMap.put(bmsUser.getId(),bmsUser);
                }
            }
        }
        return bmsUserMap;
    }


    public static String getLoginName(BmsUser bmsUser){
        String nickName = Constants.DEFAULT_USER_NAME;
        if(bmsUser != null) {
            nickName = bmsUser.getLoginName();
            if (nickName == null) {
                SystemUser systemUser = bmsUser.getSystemUser();
                if (systemUser != null) {
                    nickName = systemUser.getLoginName();
                    if (nickName == null) {
                        nickName = Constants.DEFAULT_USER_NAME;
                    }
                }
            }
        }
        return nickName;
    }

    public static String getWechatLoginName(BmsUser bmsUser){
        String nickName = Constants.DEFAULT_USER_NAME;
        if(bmsUser != null) {
            if (bmsUser.getSystemUser() != null && StringUtils.isNotBlank(bmsUser.getSystemUser().getLoginName())) {
                nickName = bmsUser.getSystemUser().getLoginName();
            }else{
                if(StringUtils.isNotBlank(bmsUser.getLoginName())){
                    nickName = bmsUser.getLoginName();
                }
            }
        }
        return nickName;
    }

    public static String getHeadImg(BmsUser bmsUser){
        String headImg = "00";
        if(bmsUser != null && StringUtils.isNotBlank(bmsUser.getHeadImg())) {
            headImg = bmsUser.getHeadImg();
        }else if(bmsUser != null && bmsUser.getSystemUser() != null
                && StringUtils.isNotBlank(bmsUser.getSystemUser().getHeadImgUrl())) {
            headImg = bmsUser.getSystemUser().getHeadImgUrl();
        }
        return headImg;
    }

    public static String getWechatHeadOrAppHeadImg(BmsUser bmsUser){
        String headImg = "00";
        if(bmsUser != null) {
            if (bmsUser.getSystemUser() != null
                    && StringUtils.isNotBlank(bmsUser.getSystemUser().getHeadImgUrl())) {
                headImg = bmsUser.getSystemUser().getHeadImgUrl();
            } else {
                if (StringUtils.isNotBlank(bmsUser.getHeadImg())) {
                    headImg = bmsUser.getHeadImg();
                }
            }
        }
        return headImg;
    }

    public static String getWechatHeadImg(BmsUser bmsUser){
        String headImg = "00";
        if(bmsUser != null && bmsUser.getSystemUser() != null
                && StringUtils.isNotBlank(bmsUser.getSystemUser().getHeadImgUrl())) {
            headImg = bmsUser.getSystemUser().getHeadImgUrl();
        }
        return headImg;
    }

    public Map<String, Object> registerUserByExternal(String phone, String unionId) {
        BmsUser bmsUser = bmsUserDao.findByPhone(phone);
        boolean needIsRegister = false;
        if(bmsUser == null) {
            if (StringUtils.isNotBlank(unionId)) {
                bmsUser = bmsUserDao.findByUnionid(unionId);
            }
            if(bmsUser == null){
                needIsRegister = true;
            }else {
                if(StringUtils.isBlank(bmsUser.getPhone())) {
                    Map<String, Object> retBind = userBindPhoneToSystemUser(bmsUser.getAccountId(), phone);
                    if (retBind.containsKey("status") && ResultCode.CODE_NORMAL.equals(retBind.get("status").toString())) {
                        bmsUser.setPhone(phone);
                    }
                }else {
                    needIsRegister = true;
                }
            }
        }
        if(needIsRegister){
            Map<String,Object> registerMap = this.creatNewUser(phone,"",Constants.COMMON_FLAG_TRUE,Constants.GENERAL_USER_ROLE_ID);
            if(!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
                return registerMap;
            }
            bmsUser = (BmsUser) registerMap.get("bmsUser");

        }
        bmsUser = TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        String token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(BmsDxClientRoleService.generalUserRoleId));
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("bmsUser",bmsUser);
        resultMap.put("token",token);
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Integer countUserTotal(Date endTime) {
        Map<String,Object> conditionMap = new LinkedHashMap<>();
        conditionMap.put("newTime_LTT",endTime);
        conditionMap.put("dxshh_NOLIKES","X00999");
        Set<Integer> createWays = new HashSet<>();
        createWays.add(2);
        createWays.add(3);
        createWays.add(4);
        conditionMap.put("createWay_IN",createWays);
        List<BmsUser> bmsUsers = bmsUserDao.findAll(new SpecificationUtils(conditionMap));
        return bmsUsers.size();
    }

    public Integer countUserRegister(Date startTime,Date endTime) {
        Map<String,Object> conditionMap = new LinkedHashMap<>();
        conditionMap.put("newTime_GTTE",startTime);
        conditionMap.put("newTime_LTT",endTime);
        conditionMap.put("dxshh_NOLIKES","X00999");
        Set<Integer> createWays = new HashSet<>();
        createWays.add(2);
        createWays.add(3);
        createWays.add(4);
        conditionMap.put("createWay_IN",createWays);
        List<BmsUser> bmsUsers = bmsUserDao.findAll(new SpecificationUtils(conditionMap));
        return bmsUsers.size();
    }

    public Map<String, Object> deleteTest(Integer userId) {
        //先删除角色
        List<BmsDxClientRole> bmsDxClientRole = bmsDxClientRoleService.getUserClienRole(userId,1);
        if(bmsDxClientRole.size() > 0){
            bmsDxClientRoleService.getBaseDao().deleteAll(bmsDxClientRole);
        }
        Optional<BmsUser> bmsUser = bmsUserDao.findById(userId);
        if(bmsUser.isPresent()){
            bmsUserDao.delete(bmsUser.get());
        }
        //删除用户
        return ResultMapHelper.success();
    }

    public BmsUser findByPhone(String phone) {
        return bmsUserDao.findByPhone(phone);
    }

    public Map<String, Object> loginByPhoneAndVerCode(String phone, String verificationCode,Integer createWay
            ,Map<String,Object> extendData) {
        if(!IdentifyCode.checkIdentifyCode(phone,verificationCode,loginCodeType)){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"验证码错误");
        }
        BmsUser bmsUser = bmsUserDao.findByPhone(phone);
        if(bmsUser == null) {
            Map<String, Object> registerMap = this.creatNewUser(phone, "", Constants.COMMON_FLAG_TRUE, Constants.GENERAL_USER_ROLE_ID);
            if (!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))) {
                return registerMap;
            }
            bmsUser = (BmsUser) registerMap.get("bmsUser");
            if (createWay != null) {
                bmsUser.setCreateWay(createWay);
            }
            if(extendData.containsKey("userTag")){
                bmsUser.setUserTag(extendData.get("userTag").toString());
            }
        }
        bmsUser = TokenManager.setUser(bmsUser);
        String token = TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(BmsDxClientRoleService.generalUserRoleId));
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("bmsUser",bmsUser);
        resultMap.put("token",token);
        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String,Object> updateUserByMinApp(ParamsMap paramsMap){
        Integer userIdentify = paramsMap.getInteger("userIdentify");
        BmsUser bmsUser = TokenManager.getUser(userIdentify);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.USER_TOKEN_INVALID,"用户不存在");
        }
        String sex = paramsMap.getString("sex");
        String loginName = paramsMap.getString("loginName");
        String birthday = paramsMap.getString("birthday");
        String headImgUrl = paramsMap.getString("headImgUrl");
        Map<String,Object> sendParams = new HashMap<>();
        if(StringUtils.isNotBlank(sex)){

            bmsUser.setSex(Constants.COMMON_FLAG_TRUE_INT);
            if(sex.equals("01") || sex.equals("女性")){
                bmsUser.setSex(Constants.COMMON_FLAG_FALSE_INT);
            }
            if(bmsUser.getSex() == Constants.COMMON_FLAG_FALSE_INT) {
                sendParams.put("sex", "01");
            }else if(bmsUser.getSex() == Constants.COMMON_FLAG_TRUE_INT){
                sendParams.put("sex", "00");
            }
        }
        if(StringUtils.isNotBlank(loginName)){
            sendParams.put("login_name", loginName);
            bmsUser.setLoginName(loginName);
        }
        if(StringUtils.isNotBlank(birthday)){
            sendParams.put("birthdate", birthday);
            bmsUser.setBirthday(birthday);
        }
        if(StringUtils.isNotBlank(headImgUrl)){
            sendParams.put("head_img_url", headImgUrl);
            bmsUser.setHeadImg(headImgUrl);
        }
        //更新到用户体系
        String accountId = bmsUser.getAccountId();
        if(StringUtils.isNotBlank(accountId)){
            sendParams.put("accountId",accountId);
            try {
                String updateUserUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/updateinfo";
                String responseBody = RestTemplateUtils.postForEntityForJson(updateUserUrl,sendParams);
                log.info("更新结果：" + responseBody);
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
        TokenManager.setUser(bmsUser);
        bmsUserChatService.reloadJGGenUser(bmsUser,Constants.GENERAL_USER_ROLE_ID);
        return ResultMapHelper.success(bmsUser,"修改成功");
    }

    public boolean updateSystemUser(UpdateAccountUserVo updateAccountUserVo){
        try {
            String updateUserUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/updateinfo";
            String responseBody = RestTemplateUtils.postForEntityForJson(updateUserUrl,BeanUtils.objectToMap(updateAccountUserVo));
            log.info("更新结果：" + responseBody);
            return true;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public Map<String, Object> userBindPhone_v2(Integer userId, String phone, String identifyCode,Integer loginWay) {
        final int WX_LOGIN = 1;
        final int IOS_LOGIN = 2;
        if(loginWay == null){
            loginWay = createByWeChatThirdParty;
        }
        Map<String,Object> userDataMap = new HashMap();
        if(!PatternMatchUtils.checkPhone(phone)){
            userDataMap.put("code",ResultCode.CODE_USER_PHONE_ERROR);
            userDataMap.put("msg","手机号码格式错误");
            return ResultMapHelper.success(userDataMap,ResultMsg.HAND_SUCCESS);
        }
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,bindPhoneCodeType)){
            userDataMap.put("code",ResultCode.CODE_IDENTIFY_CODE_ERROR);
            userDataMap.put("msg",ResultMsg.CODE_IDENTIFY_CODE_ERROR);
            return ResultMapHelper.success(userDataMap,ResultMsg.HAND_SUCCESS);
        }
        BmsUser originUser = TokenManager.getUser(userId);
        if(originUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,ResultMsg.CODE_USER_NO_EXIST);
        }
        BmsUser bmsUser = bmsUserDao.findByPhone(phone);
        if(bmsUser != null){
            if(userId.intValue() == bmsUser.getId().intValue()){
                userDataMap.put("code",ResultCode.CODE_USER_PHONE_BIND_USER);
                userDataMap.put("msg","你当前已经绑定该手机号");
                return ResultMapHelper.success(userDataMap,ResultMsg.HAND_SUCCESS);
                //return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_BIND_USER,"你当前已经绑定该手机号");
            }
            if(StringUtils.isBlank(originUser.getPhone())){
                if(loginWay == WX_LOGIN) {
                    if (StringUtils.isBlank(bmsUser.getUnionid())) {
                        userDataMap.put("code", ResultCode.CODE_PHONE_BIND_WX);
                        userDataMap.put("msg", ResultCode.CODE_PHONE_BIND_WX_MSG);
                        userDataMap.put("loginName", Constants.DEFAULT_USER_NAME);
                        if (StringUtils.isNotBlank(bmsUser.getLoginName())) {
                            userDataMap.put("loginName", bmsUser.getLoginName());
                        }
                        return ResultMapHelper.success(userDataMap, ResultMsg.HAND_SUCCESS);
                    } else {
                        userDataMap.put("code", ResultCode.CODE_PHONE_WX_EXIST);
                        userDataMap.put("msg", ResultCode.CODE_PHONE_WX_EXIST_MSG);
                        return ResultMapHelper.success(userDataMap, ResultMsg.HAND_SUCCESS);
                        //return ResultMapHelper.result(ResultCode.CODE_PHONE_WX_EXIST, ResultCode.CODE_PHONE_WX_EXIST_MSG);
                    }
                }else if(loginWay == IOS_LOGIN){
                    if(StringUtils.isBlank(bmsUser.getIosUserId())){
                        userDataMap.put("code", ResultCode.CODE_PHONE_BIND_IOS);
                        userDataMap.put("msg", ResultMsg.MSG_PHONE_BIND_IOS);
                        userDataMap.put("loginName", Constants.DEFAULT_USER_NAME);
                        if (StringUtils.isNotBlank(bmsUser.getLoginName())) {
                            userDataMap.put("loginName", bmsUser.getLoginName());
                        }
                        return ResultMapHelper.success(userDataMap, ResultMsg.HAND_SUCCESS);
                    }else {
                        userDataMap.put("code", ResultCode.CODE_PHONE_IOS_EXIST);
                        userDataMap.put("msg", ResultMsg.MSG_PHONE_IOS_EXIST);
                        return ResultMapHelper.success(userDataMap, ResultMsg.HAND_SUCCESS);
                    }
                }
            }
            userDataMap.put("code",ResultCode.CODE_USER_PHONE_EXIST);
            userDataMap.put("msg","手机号已被绑定");
            return ResultMapHelper.success(userDataMap,ResultMsg.HAND_SUCCESS);
            //return ResultMapHelper.result(ResultCode.CODE_USER_PHONE_EXIST,"手机号已被绑定");
        }
        bmsUser = originUser;
        String accountId = bmsUser.getAccountId();
        Map<String,Object> retBind = userBindPhoneToSystemUser(accountId,phone);
        if(!(retBind.containsKey("status") && ResultCode.CODE_NORMAL.equals(retBind.get("status").toString()))){
            userDataMap.put("code",retBind.get("status").toString());
            userDataMap.put("msg",retBind.get("msg").toString());
            return ResultMapHelper.success(userDataMap,ResultMsg.HAND_SUCCESS);
            //return retBind;
        }
        bmsUser.setPhone(phone);
        TokenManager.setUser(bmsUser,TokenManager.redisKeyByUserId,bmsUser.getId().toString());
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("phone",phone);
        resultMap.put("userid",userId);
        resultMap.put("code",ResultCode.CODE_NORMAL);
        resultMap.put("msg","绑定成功");
        return ResultMapHelper.success(resultMap,"绑定成功");
    }

    public Map<String, Object> mandatoryBinding(ParamsMap paramsMap) {
        String phone = paramsMap.getString("phone");
        String identifyCode = paramsMap.getString("identifyCode");
        Integer userId = paramsMap.getInteger("userIdentify");
        if(!IdentifyCode.checkIdentifyCode(phone,identifyCode,bindPhoneCodeType)){
            return ResultMapHelper.result(ResultCode.CODE_IDENTIFY_CODE_ERROR,ResultMsg.CODE_IDENTIFY_CODE_ERROR);
        }
        BmsUser unionIdUser = TokenManager.getUser(userId);
        if(StringUtils.isNotBlank(unionIdUser.getPhone())){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"该微信已绑定手机号");
        }
        if(unionIdUser == null){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_05,ResultMsg.CODE_USER_NO_EXIST);
        }
        String unionId = unionIdUser.getUnionid();
        if(unionId == null){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"请先绑定微信");
        }
        BmsUser bmsUser = this.findByPhone(phone);
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_05,"该手机号找不到用户");
        }
        String miniOpenId = null;
        if(this.mergeAccount(unionId,phone)){
            unionIdUser.setUnionid(null);
            miniOpenId = unionIdUser.getMinOpenid();
            unionIdUser.setMinOpenid(null);
            TokenManager.setUser(unionIdUser);
            if(StringUtils.isNotBlank(miniOpenId)) {
                bmsUser.setMinOpenid(miniOpenId);
            }
            bmsUser.setUnionid(unionId);
            //读取数据
            LoginVo loginVo = new LoginVo();
            loginVo.setUserid(bmsUser.getId());
            loginVo.setPhone(bmsUser.getPhone());
            loginVo.setToken(TokenUtils.getToken(bmsUser.getId().toString(),String.valueOf(BmsDxClientRoleService.generalUserRoleId)));
            loginVo.setIsBindWeChat(Constants.COMMON_FLAG_TRUE_INT);
            //判断是否加群
            loginVo.setIsRegisterGroup(bmsUserChatService.checkUserHavingGroup(bmsUser.getId(),Constants.GENERAL_USER_ROLE_ID));
            if(bmsUser.getAccountId() != null) {
                bmsUser.setSystemUser(findSystemUser(bmsUser.getAccountId()));
            }
            TokenManager.setUser(bmsUser);
            if(bmsUser.getSystemUser() != null && StringUtils.isNotBlank(bmsUser.getSystemUser().getLoginName())) {
                loginVo.setWechatName(bmsUser.getSystemUser().getLoginName());
            }else {
                loginVo.setWechatName("");
            }
            loginVo.setFxRole(fxCenterService.getFxRole(bmsUser.getId()));
            return ResultMapHelper.success(loginVo,ResultMsg.HAND_SUCCESS);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
    }


    public boolean mergeAccount(String unionId, String phone) {
        try {
            String mergeAccountUrl = AppConfig.getProperty("syniUserAddress") + "/syni_user/user/mergeAccount";
            Map<String,Object> paramsMap = new HashMap<>();
            paramsMap.put("unionId",unionId);
            paramsMap.put("phoneNo",phone);
            String responseBody = RestTemplateUtils.postForEntity(mergeAccountUrl,paramsMap);
            if(StringUtils.isNotBlank(responseBody)){
                Map<String,Object> retMap = JSON.parseObject(responseBody);
                if(retMap.containsKey("status") && "30110".equals(retMap.get("status").toString())){
                    return true;
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public void saf(){
        
    }

    public Map<String,Object> sendUserIdentifingCode(GetIdentifyingCodeDto getIdentifyingCodeDto) {
        Map<Integer,Integer> businessClient = IdentifyCode.initBusinessClient();
        //获取参数
        String phone = getIdentifyingCodeDto.getPhone();
        if(IdentifyCode.checkPhoneIdentifySendNum(phone)){
            return ResultMapHelper.result(ResultCode.CODE_IDENTIFY_CODE_SEND_MAX_NUM,"该手机号今日验证码发送超过最大限制");
        }
        Integer codeType = getIdentifyingCodeDto.getCodeType();
        String code = IdentifyCode.getIdentifyCode();

        System.out.println(code);
        //异步发送短信
        String[] params = {code};
        if(BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)){
            if(businessClient.containsKey(codeType)){
                SmsUtils.send(phone,"templateId",params,"business");
            }else {
                SmsUtils.send(phone,"templateId",params);
            }
        }
        //添加进redis
        IdentifyCode.addIdentifyCodeToRedis(phone,code,codeType);
        if(BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)){
            return ResultMapHelper.success();
        }
        return ResultMapHelper.success(code,"获取成功");
    }

    public void tegag() {
        fxCenterService.test();
    }

    public Map<String, Object> userBindOperationIOS(ParamsMap paramsMap) {
        BmsUser bmsUser = TokenManager.getUser(paramsMap.getInteger("userIdentify"));
        final int BIND_HANDLER = 1;
        final int CANCEL_BIND_HANDLER = 2;
        Integer handler = paramsMap.getInteger("handler");
        String iosUserId = paramsMap.getString("iosUserId");
        if(handler == BIND_HANDLER){
            BmsUser iosUser = bmsUserDao.findByIosUserId(iosUserId);
            if(iosUser != null){
                return ResultMapHelper.result(ResultCode.CODE_USER_IOS_BIND,ResultMsg.MSG_USER_IOS_BIND);
            }
            String iosAuthCode = paramsMap.getString("iosAuthCode");
            JSONObject data;
            try {
                data = this.getIosLoginData(iosAuthCode);
                //data = new JSONObject();
                //data.put("sub",iosUserId);
                //data.put("email","8430155984@qq.com");
                if(data.containsKey("sub") && StringUtils.checkNullAndEmpty(data.get("sub"))){
                    String sub = data.getString("sub");
                    String email = data.getString("email");
                    if(!sub.equals(iosUserId)){
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_PARAM_ERROR);
                    }
                    bmsUser.setIosTag(email);
                    bmsUser.setIosUserId(sub);
                    TokenManager.setUser(bmsUser);
                    Map<String,Object> resultMap = new HashMap<>();
                    resultMap.put("iosTag",bmsUser.getIosTag());
                    resultMap.put("isBindIos",Constants.COMMON_FLAG_TRUE_INT);
                    return ResultMapHelper.success(resultMap,ResultMsg.HAND_SUCCESS);
                }
            }catch (Exception e){
                log.error("ios login error : ",e);
                return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
            }
        }else if(handler == CANCEL_BIND_HANDLER){
            bmsUser.setIosTag(null);
            bmsUser.setIosUserId(null);
            TokenManager.setUser(bmsUser);
            return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
        }else {
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_PARAM_ERROR);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_ERROR_PARAM_ERROR);
    }

    public Map<String, Object> registerLoginByThirdChannel(String phone, Integer channel) {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        BmsUser bmsUser = bmsUserDao.findByPhone(phone);
        if(bmsUser == null){
            Map<String,Object> registerMap = this.creatNewUser(phone,"",Constants.COMMON_FLAG_TRUE,userType);
            if(!(registerMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(registerMap.get("status").toString()))){
                return registerMap;
            }
            bmsUser = (BmsUser) registerMap.get("bmsUser");
            bmsUser.setRegisterIp(requestHeaderData.getString("x-forwarded-for"));
            if(channel == Constants.THIRD_CHANNEL_ZHT){
                bmsUser.setUserTag("珠海通");
                bmsUser.setChannel(Constants.THIRD_CHANNEL_ZHT_DATA);

            }
        }
        if(bmsUser == null){
            return ResultMapHelper.result(ResultCode.CODE_USER_NO_EXIST,"用户不存在");
        }
        if(bmsUser.getIsFreeze() != null && bmsUser.getIsFreeze() == Constants.COMMON_FLAG_TRUE_INT){
            return ResultMapHelper.result(ResultCode.CODE_USER_IS_FREEZE,"账号已被冻结");
        }
        //更新登录时间
        bmsUser.setLoginTime(new Date());
        bmsUserDao.save(bmsUser);
        //更新角色
        Map<String,Object> roleMap = bmsDxClientRoleService.addRegisterUserRole(bmsUser.getId(),userType);
        BmsDxClientRole bmsDxClientRole = (BmsDxClientRole) roleMap.get("data");
        //注册后续操作
        registerLoginPost(bmsUser,bmsDxClientRole.getRoleId());
        bmsUser = TokenManager.getUser(bmsUser.getId());
        //查询是否在活动期间注册
        Map<String,Object> resultMap = new HashMap<>();
        String token = TokenUtils.getToken(bmsUser,String.valueOf(BmsDxClientRoleService.generalUserRoleId));
        resultMap.put("token",token);
        resultMap.put("phone",phone);
        return ResultMapHelper.success(resultMap,"登录成功");
    }
}
